<?php
	if (!defined('BASEPATH')) exit('No direct script access allowed');

	class MY_Loader extends CI_Loader {
		/**
		 * Constructor
		 */
		function MY_Loader(){
			parent::CI_Loader();
		}

		function view($view, $vars = array(), $return = FALSE)
		{
			$this->helper('url');
			$CI =& get_instance();

			//cargamos el lang si es necesario
			if(!isset($CI->locale)) $CI->load->library('locale'); // I18n library
			$CI->config->load('whilewairport',TRUE,FALSE);
			$idiom = $CI->config->item('def_lang', 'whilewairport');
			if (strpos($view,'/')!==0 && ( file_exists(APPPATH.'language/'.strtolower($CI->locale->get()).'/'.$view.'_lang.php') || file_exists(APPPATH.'language/'.strtolower($idiom).'/'.$view.'_lang.php')))
			{
				$CI->lang->load($view, $CI->locale->get());
			}
			//cargamos la plantilla apropiada
			$CI->config->load('whilewairport',TRUE,FALSE);
			$default_templates = $CI->config->item('default_templates', 'whilewairport');

			$base = preg_split('/\./',trim(str_replace('http://', '', base_url())));
			$layout = '';

			if (strpos($view,'/')===0)
				$view = $view;
			else{
				if ($base[0] != 'whilewairport' && file_exists(APPPATH.'views/'.$base[0].'/'.$view.'.php')){
					// Soporte para ficheros _layout.php
					if ( substr($view,strrpos($view,'/')+1,1)!='_' && file_exists(APPPATH.'views/'.$base[0].'/'.substr($view,0,strrpos($view,'/')).'/_layout.php') ){
						$layout = $base[0].'/'.substr($view,0,strrpos($view,'/')).'/_layout.php';

					}
					// ------

					$view = $base[0].'/'.$view;
				}else{
					if ( substr($view,strrpos($view,'/')+1,1)!='_' && file_exists(APPPATH.'views/'.$default_templates.'/'.substr($view,0,strrpos($view,'/')).'/_layout.php') ){
						$layout = $default_templates.'/'.substr($view,0,strrpos($view,'/')).'/_layout.php';
					}
					// ------
					$view = $default_templates.'/'.$view;
				}
			}

			if($layout !=''){
				$vars['_content'] = parent::_ci_load(array('_ci_view' => $view, '_ci_vars' => $this->_ci_object_to_array($vars), '_ci_return' => TRUE));
				$vars['scripts'] = array_unique( array_merge( ( (isset($vars['scripts']) )?$vars['scripts']:array() ) , get_head_scripts( $vars['_content'] ) ) );
				$vars['styles'] = array_unique( array_merge( ( (isset ($vars['styles']) )?$vars['styles']:array() ) , get_head_styles( $vars['_content'] ) ) );
			}
			return parent::_ci_load(array('_ci_view' => (($layout!='')?$layout:$view), '_ci_vars' => $this->_ci_object_to_array($vars), '_ci_return' => $return));
		}

	}

/* End of MY_Loader.php */